<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\Wallet;
use app\common\model\WalletToken;
use think\Db;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $rows = $list->items();
            foreach ($rows as &$row) {
                $row['usdt_balance'] = model('wallet')->where(['uid' => $row['id'], 'coin_id' => Wallet::usdt_id()])->value('balance');
                $row['level_name'] = Db::name('user_level')->where(['id' => $row['level']])->value('name');
            }
            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 用户信息
    */
    public function userinfo($uid)
    {
        $row = $this->model->get($uid);
        $this->view->assign('row', $row);
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));

        return $this->view->fetch();
    }

    /**
     * 给会员充值
    */
    public function recharge($uid)
    {
        $wallet = model('wallet')->alias('w')->join('wallet_token wt', 'w.coin_id=wt.id', 'left')->where(['w.uid' => $uid, 'wt.status' => 'normal'])->select();
        if (empty($wallet) && $this->request->isPost()) {
            $res = Wallet::create_wallet(0, $uid);
            if ($res['error'] > 0) {
                $this->error($res['msg']);
            } else {
                $this->success('创建成功');
            }
        } elseif ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post();
            if ($params) {
                $wallet_token = WalletToken::walletTokenList();
                foreach ($wallet_token as $item) {
                    $data = [];
                    if ($params['balance_' . $item['id']] > 0) {
                        $data['balance'] = $params['balance_' . $item['id']];
                    }
                    if ($params['freeze_' . $item['id']] > 0) {
                        $data['freeze'] = $params['freeze_' . $item['id']];
                    }
                    if (!empty($data)) {
                        Wallet::update($data, ['uid' => $params['uid'], 'coin_id' => $params['coin_id_' . $item['id']]]);
                    }
                }
                $this->success('充值完成');
            } else {
                $this->error('没有充值');
            }
        } else {
            foreach ($wallet as &$item) {
                $item['coin_name'] = Db::name('wallet_token')->where(['id' => $item['coin_id']])->value('title_en');
                $item['address'] = Db::name('wallet_address')->where(['wallet_id' => $item['id']])->value('address');
            }
        }
        $this->view->assign('uid', $uid);
        $this->view->assign('wallet', $wallet);

        return $this->view->fetch();
    }
}
